package com.all.play.myapplication.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.all.play.myapplication.R;
import com.all.play.myapplication.bean.MediaLocalVideoItem;
import com.all.play.myapplication.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.all.play.myapplication.R.id.tv_gone_time;

/**
 * Created by 聪明一只哈 on 2018/3/29.
 */

public class MyViderPlayerActivity extends Activity implements View.OnClickListener{

    private static final int PROGRESSES = 1;
    private VideoView videoView;
    private Uri data;


    private LinearLayout llTop;
    private TextView videoName;
    private ImageView ivBattery;
    private TextView tvSystem;
    private Button btnVoice;
    private SeekBar seekBarVoice;
    private Button switchPlay;
    private LinearLayout llBottom;
    private TextView tvGoneTime;
    private SeekBar seekBarVideoProgress;
    private TextView tvTotalTime;
    private Button btnExit;
    private Button btnVideoPre;
    private Button btnOnOffVideo;
    private Button btnNextVideo;
    private Button btnSwitchVideo;
    private Utils utils;
    private MyBattaryReceiver battaryReceiver;
    private int position;
    private List<MediaLocalVideoItem> medialist;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initData();

        findViews();



        setOnListener();


        //获取传递过来的视频uri或列表数据
        getData();

        //将传递过来的视频uri或列表数据加载,显示
        setData();

        //显示控制面板
        //videoView.setMediaController(new MediaController(this));
    }

    /**
     *加载数据
     *@author 聪明一只哈
     *@time 2018/3/30 9:58
     */
    private void setData() {
        if(medialist!=null){
            MediaLocalVideoItem mediaLocalVideoItem = medialist.get(position);
            videoName.setText(mediaLocalVideoItem.getName());
            videoView.setVideoPath(mediaLocalVideoItem.getData());


        }else if(data!=null){
            videoView.setVideoURI(data);
        }
    }

    /**
     *获取数据
     *@author 聪明一只哈
     *@time 2018/3/30 9:58
     */
    private void getData() {
        data = getIntent().getData();

        medialist = (List<MediaLocalVideoItem>) getIntent().getSerializableExtra("videolist");
        position = getIntent().getIntExtra("position", 0);

    }

    private void initData() {
        utils = new Utils();

        //注册电量变化的广播
        battaryReceiver = new MyBattaryReceiver();
        IntentFilter intentfilter=new IntentFilter();
        intentfilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        intentfilter.addAction(Intent.ACTION_BATTERY_OKAY);
        intentfilter.addAction(Intent.ACTION_BATTERY_LOW);
        registerReceiver(battaryReceiver,intentfilter);

    }

    /**
     *电量变化广播
     *@author 聪明一只哈
     *@time 2018/3/30 8:54
     */
    class MyBattaryReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {

            int battarylevel = intent.getIntExtra("level", 0);

            switchBattary(battarylevel);
        }
    }

    /**
     *根据电量来设置显示图片
     *@author 聪明一只哈
     *@time 2018/3/30 8:57
     */
    private void switchBattary(int battarylevel) {
       if(battarylevel<=0){
            ivBattery.setImageResource(R.drawable.ic_battery_0);
       }else if(battarylevel>0&&battarylevel<=10){
           ivBattery.setImageResource(R.drawable.ic_battery_10);

       }else if(battarylevel>10&&battarylevel<=20){
           ivBattery.setImageResource(R.drawable.ic_battery_20);

       }else if(battarylevel>20&&battarylevel<=40){
           ivBattery.setImageResource(R.drawable.ic_battery_40);

       }else if(battarylevel>40&&battarylevel<=60){
           ivBattery.setImageResource(R.drawable.ic_battery_60);

       }else if(battarylevel>60&&battarylevel<=80){
           ivBattery.setImageResource(R.drawable.ic_battery_80);

       }else if(battarylevel>80&&battarylevel<=100){
           ivBattery.setImageResource(R.drawable.ic_battery_100);

       }else {
           ivBattery.setImageResource(R.drawable.ic_battery_100);

       }
    }

    /**
     *监听
     *@author 聪明一只哈
     *@time 2018/3/29 16:58
     */
    private void setOnListener() {
        //videoview播放前的准备的监听
        videoView.setOnPreparedListener(new MyPrepareListener());

        //videoview播放时的错误的监听
        videoView.setOnErrorListener(new MyOnErrorListener());

        //videoview播放完的结束后的监听
        videoView.setOnCompletionListener(new MyOnCompletedListener());

        //seekbar拖动监听
        seekBarVideoProgress.setOnSeekBarChangeListener(new MyOnSeekTouchChangeListener());

    }



    /**
     * Find the Views in the layout<br />
     * <br />
     * Auto-created on 2018-03-29 16:19:34 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    private void findViews() {
        setContentView(R.layout.activity_myvideo_player);

        videoView = (VideoView) findViewById(R.id.video_view);
        llTop = (LinearLayout)findViewById( R.id.ll_top );
        videoName = (TextView)findViewById( R.id.video_name );
        ivBattery = (ImageView)findViewById( R.id.iv_battery );
        tvSystem = (TextView)findViewById( R.id.tv_system );
        btnVoice = (Button)findViewById( R.id.btn_voice );
        seekBarVoice = (SeekBar)findViewById( R.id.seekBar_voice );
        switchPlay = (Button)findViewById( R.id.switch_play );
        llBottom = (LinearLayout)findViewById( R.id.ll_bottom );
        tvGoneTime = (TextView)findViewById( tv_gone_time );
        seekBarVideoProgress = (SeekBar)findViewById( R.id.seekBar_video_progress );
        tvTotalTime = (TextView)findViewById( R.id.tv_total_time );
        btnExit = (Button)findViewById( R.id.btn_exit );
        btnVideoPre = (Button)findViewById( R.id.btn_video_pre );
        btnOnOffVideo = (Button)findViewById( R.id.btn_on_off_video );
        btnNextVideo = (Button)findViewById( R.id.btn_next_video );
        btnSwitchVideo = (Button)findViewById( R.id.btn_switch_video );

        btnVoice.setOnClickListener( this );
        switchPlay.setOnClickListener( this );
        btnExit.setOnClickListener( this );
        btnVideoPre.setOnClickListener( this );
        btnOnOffVideo.setOnClickListener( this );
        btnNextVideo.setOnClickListener( this );
        btnSwitchVideo.setOnClickListener( this );
    }

    /**
     * Handle button click events<br />
     * <br />
     * Auto-created on 2018-03-29 16:19:34 by Android Layout Finder
     * (http://www.buzzingandroid.com/tools/android-layout-finder)
     */
    @Override
    public void onClick(View v) {
        if ( v == btnVoice ) {
            // Handle clicks for btnVoice
        } else if ( v == switchPlay ) {
            // Handle clicks for switchPlay
        } else if ( v == btnExit ) {
            // Handle clicks for btnExit
        } else if ( v == btnVideoPre ) {
            // Handle clicks for btnVideoPre
        } else if ( v == btnOnOffVideo ) {
            // 播放-->暂停 / 暂停-->播放
            if(videoView.isPlaying()){
                videoView.pause();
                btnOnOffVideo.setBackgroundResource(R.drawable.bt_start_selector);
            }else{
                videoView.start();
                btnOnOffVideo.setBackgroundResource(R.drawable.bt_pause_selector);

            }

        } else if ( v == btnNextVideo ) {
            // Handle clicks for btnNextVideo
        } else if ( v == btnSwitchVideo ) {
            // Handle clicks for btnSwitchVideo
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case PROGRESSES:

                    int currentPosition = videoView.getCurrentPosition();
                    //设置进度
                    seekBarVideoProgress.setProgress(currentPosition);
                    //设置进度时间
                    tvGoneTime.setText(utils.stringForTime(currentPosition));

                    //电池右边设置系统时间
                    tvSystem.setText(getSystemTime());

                    handler.removeMessages(PROGRESSES);
                    handler.sendEmptyMessageDelayed(PROGRESSES,1000);

                    break;

                default:

                    break;
            }
        }
    };

    /**
     *设置系统的时间
     *@author 聪明一只哈
     *@time 2018/3/30 9:08
     */
    private String getSystemTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        return dateFormat.format(new Date());
    }


    /**
     *seekbar滑动的监听
     *@author 聪明一只哈
     *@time 2018/3/30 8:43
     */
    class MyOnSeekTouchChangeListener implements SeekBar.OnSeekBarChangeListener {


        /**
         * 进度改变
         * @param seekBar
         * @param progress
         * @param fromUser  用户拖动 true ;系统 进度变化也会调用,值为false
         */
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(fromUser){
                videoView.seekTo(progress);
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    }

    /**
     *播放前的监听
     *@author 聪明一只哈
     *@time 2018/3/29 13:45
     */
    class MyPrepareListener implements MediaPlayer.OnPreparedListener{
        //底层解码准备好
        @Override
        public void onPrepared(MediaPlayer mp) {
            //开始播放
            videoView.start();

            int duration = videoView.getDuration();
            seekBarVideoProgress.setMax(duration);

            tvTotalTime.setText(utils.stringForTime(duration));


            handler.sendEmptyMessage(PROGRESSES);
        }
    }

    /**
     *播放错误的监听
     *@author 聪明一只哈
     *@time 2018/3/29 13:45
     */
    class MyOnErrorListener implements MediaPlayer.OnErrorListener{

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {

            return false;//false  一旦出错后,会弹出一个对话框
        }
    }

    /**
     *播放结束后的监听
     *@author 聪明一只哈
     *@time 2018/3/29 13:45
     */
    class MyOnCompletedListener implements MediaPlayer.OnCompletionListener{

        @Override
        public void onCompletion(MediaPlayer mp) {
            Toast.makeText(MyViderPlayerActivity.this, ""+ videoView.getDuration()+"~~"+videoView.getCurrentPosition(), Toast.LENGTH_SHORT).show();

        }
    }


    @Override
    protected void onDestroy() {
        if(battaryReceiver!=null){
            unregisterReceiver(battaryReceiver);
            battaryReceiver=null;
        }
        super.onDestroy();
    }
}
